package com.dha.dao.impl;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.dha.dao.DangNhapDAO;

@WebService(targetNamespace = "DangNhap")
public class DangNhapDAOImpl implements DangNhapDAO {
	private SessionFactory sessionFactory = new Configuration().configure()
			.buildSessionFactory();
	private Session session;

	@Override
	@WebMethod(operationName = "DangNhap")
	public int dangNhap(@WebParam(name = "MaSo") String maSo,
			@WebParam(name = "MatKhau") String matKhau) {
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			String sql = null;
			if (maSo.length() == 12) {
				sql = "from SinhVienEntity where maSinhVien = ? and matKhau = ?";
			} else {
				if (maSo.length() == 7) {
					sql = "from GiaoVienEntity where maGiaoVien = ? and matKhau = ?";
				} else {
					return 0;
				}
			}

			Query query = session.createQuery(sql);
			query.setParameter(0, maSo);
			query.setParameter(1, matKhau);
			session.getTransaction().commit();
			// tra ve so dong dc select, tra ve 1 la ok, khac 1 la sai, -1 la co
			// exception

			return query.list().size();
		} catch (Exception e) {
			session.getTransaction().rollback();
			return 0;
		} finally {
			session.close();
		}
	}
	
	
	@Override
	@WebMethod(operationName="ThongTin")
	public String thongTin(@WebParam(name="MaSo")String maSo) {
		try {
			session = sessionFactory.openSession();
			session.beginTransaction();
			String sql = null;
			if (maSo.length() == 12) {
				sql = "select tenSinhVien from SinhVienEntity where maSinhVien = ?";
			} else {
				if (maSo.length() == 7) {
					sql = "select tenGiaoVien from GiaoVienEntity where maGiaoVien = ?";
				} else {
					return null;
				}
			}

			Query query = session.createQuery(sql);
			query.setParameter(0, maSo);
			session.getTransaction().commit();
			return query.list().get(0).toString();
		} catch (Exception e) {
			session.getTransaction().rollback();
			return null;
		} finally {
			session.close();
		}
	}
}